<?php

namespace app\index\controller;

use think\Db as scholarDB;
use think\Log;
use think\Cache;
use traits\think\Instance;
use think\Request;

class Scholar extends Common{

    public $datas;

    /**
     * 根据条件查询学者信息,如存在则绑定学者
     */
    public function getScholarByCondition(){
        /**
         * scholarName 学者姓名
         * phone 手机号
         * unionId 微信unionId
         */
        $this->datas = $this->params;

        try{
            $this->getScholar();
        }catch (Exception $e){
            echo $e->getMessage();
        }
    }


    private function getScholar(){
        $sql = "select count(1) as flag from scholar where scholar_name = '".$this->datas['scholarName']."' and phone = '".$this->datas['phone']."' ";

        $res = scholarDB::query($sql);
        if($res[0]['flag'] == 0){
            $sql = "select scholar_name,phone from scholar where scholar_name = '".$this->datas['scholarName']."'";
            $res = scholarDB::query($sql);
            if(!empty($res)){
                $this->returnMsg(1, '获取数据成功', $res);
            }else{
                $this->returnMsg(9, '无该学者信息！');
            }
        }

        /**
         * 根据unionId查询用户信息
         */
        $userdata = $this->getUserInfo();
        if(!empty($userdata)){
            /**
             * 查询学者id
             */
            $sql = "select id from scholar where scholar_name = '".$this->datas['scholarName']."' and phone = '".$this->datas['phone']."' ";
            $res = scholarDB::query($sql);
            /**
             * 绑定学者(用户id,学者id)
             */
            $bindmsg = $this->bindScholar($userdata['id'],$res[0]['id']);
            $this->returnMsg(1, $bindmsg);
        }
        $this->returnMsg(9, '该微信未注册过或已绑定');
    }

    /**
     * 获取用户信息(未激活)
     */
    private function getUserInfo(){
        //通过openid查询
        $sql = "select id,user_name as userName,e_user_name as eUserName,institute,subject,research_direction as researchDirection"
            .",user_detail as userDetail,phone,user_img as userImg,email,address,open_id as openId,union_id as unionId,create_time as createTime,update_time as updateTime,status,scholar_id as scholarId"
            ." from user where status = 0 and union_id = '".$this->datas['unionId']."'";
        $res = scholarDB::query($sql);

        if(empty($res)){
            return null;
        }

        return $res[0];
    }

    /**
     * 绑定学者信息
     * @param $id
     * @param $scholarId
     * @return string
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    private function bindScholar($id,$scholarId){
        scholarDB::name('user')->where([
            'id'=>$id
        ])->update([
            'scholar_id'=>$scholarId,
            'status'=>1,
            'update_time'=>date('Y-m-d H:i:s')
        ]);
        return '绑定学者信息成功!';
    }
}